﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using AIS.SDK.Api.Response;
using AIS.SDK.Handler;
using AIS.SDK.Model;
using AISservice.Common;
using Common;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;

namespace AISservice.Controllers
{
    [Route("api/v1/[controller]/[action]")]
    [ApiController]
    public class P4116Controller:ControllerBase
    {

        /// <summary>
        /// F5单增加，使用Apps方式调用
        /// </summary>
        /// <param name="objpram"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<MQResponse> CreateF5(dynamic objpram)
        {
            Log4Net.Debug(objpram);

            Dictionary<int, string> detailinfos = new Dictionary<int, string>();
            int index = 0;


            string username = objpram["username"].ToString();
            string password = objpram["password"].ToString();
            string orderid = objpram["orderid"].ToString();
            MQResponse execresult = new MQResponse() { ResponseCode = "200" };
            int stackId = 0;
            int stateId = 0;
            string rid = "";
            string token = "";
            bool needclose = false;


            try
            {
                if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
                {
                    throw new Exception("请求的用户名或密码为空！");
                }
                token = SomeHandler.GetToken(username, password);

                if (string.IsNullOrWhiteSpace(token))
                {
                    throw new MQException("401", "验证失败，请检查用户名密码是否正确！");
                }

                Console.WriteLine($"username:{username} Token:{token}");
                Console.WriteLine($"{DateTime.Now.ToString()}  新增F5单据 {orderid}");
                #region 打开IT单列表,点击新增
                FormRequest formRequest = new FormRequest()
                {
                    //maxPageSize = "2",
                    formName = "P4116_W4116A",
                    version = "MBR001",
                    formServiceAction = "C",
                    bypassFormServiceEREvent = true,
                    formActions = new FormActionsCollection
                    (
                        new FSREvent[]
                        {
                            new FSREvent() { controlID="8", command="DoAction"  }
                        }
                    )
                };
                ApplicationStackRequest asrequest = new ApplicationStackRequest()
                {
                    action = "open",
                    outputType = "VERSION2",
                    formName = "P4116_W4116A",
                    stackId = stackId,
                    stateId = stateId,
                    formRequest = formRequest

                };

                AppstackResponse response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                #endregion
                stackId = response.stackId;
                stateId = response.stateId;
                rid = response.rid;
                if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P4116_W4116B"))
                {

                    List<gridrowInsertevents> gridrows = new List<gridrowInsertevents>();
                    FormActionsCollection fs = new FormActionsCollection();
                    DataRow lastrow = new DataTable().NewRow();
                    DataTable dt = new BLL.orderHandler().GetTransferOrderForF5(orderid)[0];
                    if (dt.Rows.Count <= 0)
                        throw new MQException("404", "无数据产生，请检查是否需要生成F5单！");

                    foreach (DataRow dr in dt.Rows)
                    {
                        gridcolumnCollection col = new gridcolumnCollection();
                        col.Add(new gridcolumnevent() { columnID = "28", value = dr["FRTO"].ToString(), command = "SetGridCellValue" });
                        col.Add(new gridcolumnevent() { columnID = "41", value = dr["ItemNumber"].ToString(), command = "SetGridCellValue" });
                        col.Add(new gridcolumnevent() { columnID = "29", value = dr["qty"].ToString(), command = "SetGridCellValue" });
                        col.Add(new gridcolumnevent() { columnID = "102", value = dr["LOCN"].ToString().Trim(), command = "SetGridCellValue" });
                        col.Add(new gridcolumnevent() { columnID = "144", value = dr["sys_linenum"].ToString().Trim(), command = "SetGridCellValue" });
                        //col.Add(new gridcolumnevent() { columnID = "42", value = dr["Batch"].ToString().Trim(), command = "SetGridCellValue" });

                        gridrows.Add(new gridrowInsertevents() { gridColumnEvents = col });
    

                        detailinfos.Add(index, SetErrLineMsg((index+1).ToString(), dr["FRTO"].ToString(),
                            dr["ItemNumber"].ToString(), dr["qty"].ToString(), dr["LOCN"].ToString()));
                        index++;
                        lastrow = dr;
                    }
                    GridAction _gridAction = new GridAction();
                    _gridAction.gridID = "1";
                    _gridAction.gridRowInsertEvents = gridrows;

                    //fs.Add(new FSREvent() { command = "SelectRow", gridAction = gridAction });
                    //fs.Add(new FSREvent() { command = "DoAction", controlID = "4" });

                    ActionRequest actionRequest = new ActionRequest()
                    {
                        formOID = "W4116B",
                        formActions = new FormActionsCollection
                                     (
                                         new FSREvent[]
                                         {

                                            new FSREvent() { controlID="26", command="SetControlValue", value=lastrow["fromBU"].ToString()},
                                            new FSREvent() { controlID="24",command="SetControlValue", value= lastrow["toBU"].ToString() },
                                            new FSREvent() { controlID="16", command="SetControlValue", value=lastrow["sys_remark"].ToString()},
                                            new FSREvent() {
                                                            controlID ="1.0",
                                                            command ="SelectRow",
                                                            gridAction =_gridAction
                                                            },

                                            new FSREvent() { controlID="4", command="DoAction"  }
                                         }
                                     )
                                 ,
                        stopOnWarning = "false"
                    };
                    asrequest = new ApplicationStackRequest()
                    {
                        outputType = "VERSION2",
                        allowCache = true,
                        action = "execute",
                        actionRequest = actionRequest,
                        stackId = response.stackId,//上一次返回的值
                        stateId = response.stateId,
                        rid = response.rid
                    };

                    response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                    needclose = true;
                    stackId = response.stackId;
                    stateId = response.stateId;
                    rid = response.rid;

                    //System.Threading.Thread.Sleep(500);
                    if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P4116_W4116B"))
                    {
                        JObject obj = response.ToJObject();
                        //应该查询到数据
                        string IAno = obj["fs_P4116_W4116B"]["data"]["z_DOCO_53"]["value"].ToString();
                        Console.WriteLine($"{DateTime.Now.ToString()} 生成F5单:{IAno}");
                        execresult.Result = IAno;
                        execresult.Message = response.JsonString;
                    }
                }
            }
            catch (Exception x)
            {
                Log4Net.Error($"请求异常:{x.Message}");
                Console.WriteLine($"{DateTime.Now.ToString()}  请求异常:{x.Message}");
                execresult.ResponseCode = CommonHandler.GetException(x.Message, "CODE", "500").ToString();
                execresult.Message = CommonHandler.GetException(x.Message, "DESC", x.Message).ToString();
                if (string.IsNullOrWhiteSpace(execresult.Message))
                {
                    execresult.Message = CommonHandler.GetException(x.Message, "TITLE", x.Message).ToString();
                }

                //2023-10-16 增加当可供量不足的时候，提示是哪一行
                int errline = CommonHandler.GetErrorControlLine(x.Message);
                if (errline >= 0)
                    execresult.Message += System.Environment.NewLine + detailinfos[errline];

                Console.WriteLine($"{DateTime.Now.ToString()}  请求返回异常:{execresult.Message}");
            }
            finally
            {
                #region Close

                ActionRequest actionRequest = new ActionRequest()
                {
                    formOID = "W4116B"
                };
                ApplicationStackRequest asrequest = new ApplicationStackRequest()
                {
                    outputType = "VERSION2",
                    allowCache = true,
                    action = "close",
                    actionRequest = actionRequest,
                    stackId = stackId,//上一次返回的值
                    stateId = stateId,
                    rid = rid
                };
                if (!string.IsNullOrWhiteSpace(token) && needclose)
                {
                    AppstackResponse response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                }
                #endregion
            }
            return execresult;
        }



        private string SetErrLineMsg(string linenum,string FRTO, string itemnumber, string qty, string invergion)
        {
            string msg = $"第{Convert.ToInt32( linenum)+1}行中【{FRTO}】的{itemnumber}本次请求数量{qty},在份额:[{invergion}]不能满足，请检查！";
            return msg;
        }


    }
}
